package com.lzh.o2o.web.shopadmin;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartFile;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.lzh.o2o.dto.ImageHolder;
import com.lzh.o2o.dto.ProductExecution;
import com.lzh.o2o.enums.ProductStateEnum;
import com.lzh.o2o.exception.ProductOperationException;
import com.lzh.o2o.pojo.Product;
import com.lzh.o2o.pojo.ProductCategory;
import com.lzh.o2o.pojo.Shop;
import com.lzh.o2o.service.ProductCategoryService;
import com.lzh.o2o.service.ProductService;
import com.lzh.o2o.util.CodeUtil;
import com.lzh.o2o.util.HttpServletRequestUtil;

/**
 * @author haohao:
 * @date 创建时间：2018年9月17日 下午1:28:54
 * @version 1.0
 * @parameter
 * @since
 * @return
 */
@Controller
@RequestMapping("/shopadmin")
public class ProductManagementController {
	@Autowired
	private ProductService productService;
	@Autowired
	private ProductCategoryService productCategoryService;
	// 支持上传商品详情图的最大数量
	private static final int IMAGEMAXCOUNT = 6;
	private static final String Shop = null;
	Logger logger=LoggerFactory.getLogger(ProductManagementController.class);

	@RequestMapping(value = "/addproduct", method = RequestMethod.POST)
	@ResponseBody
	private Map<String, Object> addProduct(HttpServletRequest request) {
		logger.info("添加商品信息开始");
		Map<String, Object> modelMap = new HashMap<String, Object>();
		// 验证码校验
		if (!CodeUtil.checkVerifyCode(request)) {
			logger.error("用户输入验证码错误");
			modelMap.put("success", false);
			modelMap.put("errMSg", "验证码输入错误");
			return modelMap;
		}
		// 接收前段参数的变量的初始化，包括商品，缩略图，详情图列表实体类
		ObjectMapper mapper = new ObjectMapper();
		Product product = null;
		//获取前端上传的json对象
		String productStr = HttpServletRequestUtil.getString(request, "productStr");
	
		// 处理缩略图
		ImageHolder thumbnail = null;
		// 处理详情图
		List<ImageHolder> productImgList = new ArrayList<ImageHolder>();
		// 从请求域中获取文件流
		CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(
				request.getSession().getServletContext());
		try {
			// 若请求中存在文件流，则取出相关的文件（包括缩略图和详情图）
			if (multipartResolver.isMultipart(request)) {
				thumbnail = handlerImage(request, thumbnail, productImgList);
			} else {
				logger.error("用户没有添加商品缩略图主图");
				modelMap.put("success", false);
				modelMap.put("errMSg", "上传图片不能为空");
			}
		} catch (Exception e) {
			logger.error("multipartResolver解析图片流失败");
			modelMap.put("success", false);
			modelMap.put("errMSg", e.toString());
			return modelMap;
		}

		try {
			// 尝试获取前段传过来的表单String流并将其转换成Product实体类
			product = mapper.readValue(productStr, Product.class);

		} catch (Exception e) {
			logger.error("将json数据转换成product对象失败");
			modelMap.put("success", false);
			modelMap.put("errMSg", e.toString());
			return modelMap;
		}
		// 若Product信息，缩略图以及详情图列表为非空，则开始进行商品添加操作
		if (product != null && thumbnail != null && productImgList.size() > 0) {
			try {
				Shop currentShop = (Shop) request.getSession().getAttribute("currentShop");
				// 防止用户传入非法的shopId
				product.setShop(currentShop);
				// 执行添加操作
				ProductExecution pe = productService.addProduct(product, thumbnail, productImgList);
				if (pe.getState() == ProductStateEnum.SUCCESS.getState()) {
					logger.info("增加商品信息成功");
					modelMap.put("success", true);
				} else {
					logger.error("添加商品失败");
					modelMap.put("success", false);
					modelMap.put("errMsg", pe.getStateInfo());
				}

			} catch (ProductOperationException e) {
				logger.error("添加商品异常");
				modelMap.put("success", false);
				modelMap.put("errMsg", e);
				return modelMap;
			}
		} else {
			logger.error("不存在商品信息");
			modelMap.put("success", false);
			modelMap.put("errMsg", "请输入商品信息");
		}
		logger.info("添加商品信息结束");

		return modelMap;
	}

	private ImageHolder handlerImage(HttpServletRequest request, ImageHolder thumbnail,
			List<ImageHolder> productImgList) throws IOException {
		MultipartHttpServletRequest	multipartRequest = (MultipartHttpServletRequest) request;
		// 取出缩略图并构建ImageHolder对象
		CommonsMultipartFile thumbnailFile = (CommonsMultipartFile) multipartRequest.getFile("thumbnail");
		if(thumbnailFile!=null){
			thumbnail = new ImageHolder(thumbnailFile.getOriginalFilename(), thumbnailFile.getInputStream());

		}
		// 取出详情图列表并构建List<ImageHolder>列表对象，最多支持六张图片上传
		for (int i = 0; i < IMAGEMAXCOUNT; i++) {
			CommonsMultipartFile productImgFile = (CommonsMultipartFile) multipartRequest
					.getFile("productImg" + i);

			if (productImgFile != null) {
				// 若取出的第i个详情图片文件流不为空，则将其加入详情列表
				ImageHolder productImg = new ImageHolder(productImgFile.getOriginalFilename(),
						productImgFile.getInputStream());
				productImgList.add(productImg);
			} else {
				// 若取出来的第i个详情图片文件流为空，则终止循环
				break;
			}
		}
		//返回图片封装类对象
		return thumbnail;
	}

	// 根据商品id查询商品信息
	@RequestMapping(value = "/getproductbyid", method = RequestMethod.GET)
	@ResponseBody
	private Map<String, Object> getProductById(@RequestParam long productId) {
		logger.info("获取商品的详细信息方法开始");
		Map<String, Object> modelMap = new HashMap<String, Object>();
		// 非空判断
		if (productId > -1) {
			// 获取商品信息
			Product product = productService.getProductById(productId);
			// 获取该商品下的商品类别列表
			List<ProductCategory> productCategoryList = productCategoryService
					.getProductCategoryList(product.getShop().getShopId());
			modelMap.put("product", product);
			modelMap.put("productCategoryList", productCategoryList);
			modelMap.put("success", true);
		} else {
			logger.error("获取商品id失败");
			modelMap.put("success", false);
			modelMap.put("errMsg", "empty productId");
		}
		logger.info("获取商品的详细信息方法结束");

		return modelMap;

	}

	@RequestMapping(value = "/modifyproduct", method = RequestMethod.POST)
	@ResponseBody
	private Map<String, Object> modifyproduct(HttpServletRequest request) throws IOException {
		logger.info("获取商品的详细信息方法结束");
		Map<String, Object> modelMap = new HashMap<String, Object>();
		// 是商品编辑时候调用还是上下架操作的时候调用
		// 若为前者进行验证码判断，后者则跳过验证码判断
		//获取状态码，是上架还是下架
		boolean statusChange = HttpServletRequestUtil.getBoolean(request, "statusChange");
		// 验证码判断
		if (!statusChange && !CodeUtil.checkVerifyCode(request)) {
			logger.error("输入的验证码错误");
			modelMap.put("success", false);
			modelMap.put("errMsg", "验证码输入错误");
			return modelMap;
		}
		// 接受前端参数的变量的初始化，包括商品，缩略图，详情图列表实体类
		ObjectMapper mapper = new ObjectMapper();
		Product product = null;
		ImageHolder thumbnail = null;
		List<ImageHolder> productImgList = new ArrayList<ImageHolder>();
		CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(
				request.getSession().getServletContext());
		// 若请求中存在文件流，则取出相关文件(包括缩略图 和详情图)
		try {
			logger.debug("获取文件流信息");
			if (multipartResolver.isMultipart(request)) {
				//判断是否有文件流信息，如果没有，无需修改图片信息
				thumbnail = handlerImage(request, thumbnail, productImgList);
			}

		} catch (ProductOperationException e) {
			logger.debug("获取文件流信息异常");
			modelMap.put("success", false);
			modelMap.put("errMsg", e.toString());
			return modelMap;
		}
		try{
			logger.debug("将前端传入的json数据转成商品实体类");
			String productStr = HttpServletRequestUtil.getString(request, "productStr");
			product = mapper.readValue(productStr, Product.class);
		}catch (ProductOperationException e) {
			logger.error("转换实体类失败");
			modelMap.put("success", false);
			modelMap.put("errMsg", e.toString());
			return modelMap;
		}
		//非空判断
		if(product!=null){
			try{
				
			
			//从session中获取当前店铺的Id并赋值给product，减少对前段数据的依赖
			Shop currentshop=(Shop) request.getSession().getAttribute("currentShop");
			product.setShop(currentshop);
			//开始进行商品信息变更操作
			ProductExecution pe = productService.modifyProduct(product, thumbnail, productImgList);
			if(pe.getState()==ProductStateEnum.SUCCESS.getState()){
				logger.debug("改变商品信息成功");
				modelMap.put("success", true);
			}else{
				logger.error("改变商品信息失败");
				modelMap.put("success", false);
				modelMap.put("errMsg", pe.getStateInfo());
			}
		}catch (ProductOperationException e) {
			logger.error("修改商品信息异常 ");
			modelMap.put("success", false);
			modelMap.put("errMsg", e.toString());
			return modelMap;
		}
		}else {
			logger.debug("前端没有输出商品信息");
			modelMap.put("success", false);
			modelMap.put("errMsg", "请输入商品信息");
		}
		logger.info("修改商品信息方法结束");
		return modelMap;
	}
	
	//获取当前店铺下的所有商品信息
	@RequestMapping(value = "/getproductlistbyshop", method = RequestMethod.GET)
	@ResponseBody
	private Map<String, Object> getProductListByShop(HttpServletRequest request) throws IOException {
		logger.info("获取店铺下的商品信息开始");
		Map<String, Object> modelMap = new HashMap<String, Object>();
		//获取前台传过来的页码
		int pageIndex = HttpServletRequestUtil.getInt(request, "pageIndex");
		//获取前台穿过来的每页要求返回的商品数上限
		int pageSize = HttpServletRequestUtil.getInt(request, "pageSize");
		//从当前session中获取店铺信息，主要是获取shopid
		Shop currentShop=(Shop)request.getSession().getAttribute("currentShop");
		//空值判断
		if((pageIndex>-1)&&(pageSize>1)&&(currentShop!=null)&&(currentShop.getShopId()!=null)){
			//获取传入需要检索 的条件，包括是否需要从某个商品类别以及模糊查找商品名去筛选某个店铺下的商品列表
			//筛选的条件可以进行排列组合
			Long productCategoryId = HttpServletRequestUtil.getLong(request, "productCategoryId");
			String ProductName = HttpServletRequestUtil.getString(request, "productName");
			//封装查询条件
			Product productCondition = compactProductCondition(currentShop.getShopId(),productCategoryId,ProductName);
			//传入查询条件以及分页信息进service进行相应商品列表以及总数
			ProductExecution pe = productService.getProductList(productCondition, pageIndex, pageSize);
			modelMap.put("productList", pe.getProductList());
			modelMap.put("count", pe.getCount());
			modelMap.put("success", true);

		}else{
			logger.debug("没有获取到分页数量与店铺id");
			modelMap.put("success", false);
			modelMap.put("errMsh", "empty pageSize or pageIndex or shopId");

		}
		logger.info("获取店铺下的商品列表信息失败");
		return modelMap;
	}
	//整合要查询的条件返回ProductCondition
	private Product compactProductCondition(Long shopId, Long productCategoryId, String productName) {
		Product productCondition = new Product();
		Shop shop = new Shop();
		shop.setShopId(shopId);
		productCondition.setShop(shop);
		//若有指定类别的要求则添加进去
		if(productCategoryId!=-1L){
			ProductCategory productCategory = new ProductCategory();
			productCategory.setProductCategoryId(productCategoryId);
			productCondition.setProductCategory(productCategory);
			
		}
		//若有上哦名模糊查询的要求则添加进去
		if(productName!=null){
			productCondition.setProductName(productName);
		}
		return productCondition;
	}
	
}